//
//  LCWaterFlowLayout.m
//  瀑布流
//
//  Created by li cheng on 16/9/12.
//  Copyright © 2016年 li cheng. All rights reserved.
//

#import "LCWaterFlowLayout.h"

@interface LCWaterFlowLayout()
@property (nonatomic, assign) CGFloat itemHeight;
@end
@implementation LCWaterFlowLayout
- (instancetype)init{
    self = [super init];
    if (self) {
        _attributesArray = [NSMutableArray array];
        _numberOfRow = 0;
        _numberOfitemInRow = 0;
        _contentWidth = 0.0f;
    }
    return self;
}
- (void)prepareLayout{
    // 清空 layoutAttributes 数组
    if (_attributesArray.count == 0) {
        [_attributesArray removeAllObjects];
    }
    for (int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
        CGFloat x = _contentWidth + 5 * _numberOfitemInRow;
//        NSLog(@"CGFloat x:%f", _contentWidth);
        CGFloat y = _numberOfRow * 50;
//        NSLog(@"CGFloat y:%ld", _numberOfRow * 50);
        CGFloat height = 40;
//        NSLog(@"CGFloat height:%f", height);
        CGFloat width = 40;
        if ([self.delegate respondsToSelector:@selector(collectionView:layout:height:widthForItemAtIndexPath:)]) {
            width = [self.delegate collectionView:self.collectionView layout:self height:height widthForItemAtIndexPath:index] + 20;
        }
//        NSLog(@"CGFloat width:%f", width);
        layoutAttributes.frame = CGRectMake(x, y, width, height);
        [_attributesArray addObject:layoutAttributes];
        _numberOfitemInRow++;
        _contentWidth = _contentWidth + width;
        // 当超过屏幕, 做下面的这些操作
        if (x + width * 2 >= self.collectionView.bounds.size.width) {
            _contentWidth = 0;
            _numberOfRow++;
            _numberOfitemInRow = 0;
        } else {
            
        }
    };
  
}

/** 返回的是, 每个item对应的布局属性 */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return _attributesArray;
}
/** 负责CollectionView的滚动范围 */
- (CGSize)collectionViewContentSize {
    
    return CGSizeMake(0, 0);
    
}







@end
